package com.ruoyi.cms.service.impl;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.ruoyi.cms.service.DashScopeService;
import com.ruoyi.common.exception.modules.CmsException;
import io.reactivex.Flowable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;

@Service
@Slf4j
public class DashScopeServiceImpl implements DashScopeService {

    private static final String model = "deepseek-v3";
    private static final String apiKey = "sk-c6a14dae080c44faa4dc9eedcc788576";

    @Override
    public GenerationResult call(String message) {
        try {
            Generation gen = new Generation();
            Message userMsg = Message.builder()
                    .role(Role.USER.getValue())
                    .content(message)
                    .build();
            GenerationParam param = GenerationParam.builder()
                    // 若没有配置环境变量，请用阿里云百炼API Key将下行替换为：.apiKey("sk-xxx")
                    .apiKey(apiKey)
                    .model(model)
                    .messages(Collections.singletonList(userMsg))
                    // 不可以设置为"text"
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .build();
            return gen.call(param);
        } catch (Exception e) {
            log.error("call error", e);
            throw new CmsException("call error");
        }
    }

    @Override
    public Flowable<GenerationResult> streamCall(String message) {
        try {
            Generation gen = new Generation();
            Message userMsg = Message.builder()
                    .role(Role.USER.getValue())
                    .content(message)
                    .build();

            GenerationParam param = buildGenerationParam(userMsg);
            return gen.streamCall(param);
        } catch (Exception e) {
            log.error("streamCall error", e);
            throw new CmsException("streamCall error");
        }
    }

    private static GenerationParam buildGenerationParam(Message userMsg) {
        return GenerationParam.builder()
                // 若没有配置环境变量，请用阿里云百炼API Key将下行替换为：.apiKey("sk-xxx")
                .apiKey(apiKey)
                .model(model)
                .messages(Collections.singletonList(userMsg))
                // 不可以设置为"text"
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .incrementalOutput(true)
                .build();
    }

}
